import axios from '../utils/axios'
import  apis from '../apis'
//menus的数据装换成树形结构
var toTree = (data)=>{
    //如果parentId为0，则表示他是树的第一元素
    var rs = {};
    for(let i=0;i<data.length;i++){
        var permission = data[i];
        if(permission.parentid == 0){
            // rs.push(permission);
            permission.children =[];
            rs[permission._id] = permission;
        }
    }    
    for(let i=0;i<data.length;i++){
        var permission = data[i];
        for(var key in rs){
            if(permission.parentid == key){
                rs[key].children.push(permission)
            }
        }
    }
    // console.log(rs)
    return rs
}
//vuex的每一个模块都有和store对象一样的属性和方法
const state = {
    allMenus:[],
    allPermissions:[],
    allRolePermission:[],
    allgames:[]
}
//vuex的计算属性
const getters = {
   allMenus(state){
       return toTree(state.allMenus);
   },
   allPermissions(state){
        // console.log(state.allPermissions)
        return toTree(state.allPermissions)
   },
   allRolePermission(state){
        return state.allRolePermission
   },
   allgames(state){
       return state.allgames
   }
  
}

// 所有同步修改的状态的行为都在mutations提供的函数里进行
const mutations = {
    LOADALLMENUS(state,payload){
        state.allMenus = payload;
    },
    LOADALLPERMISSIONS(state,payload){
        state.allPermissions = payload;
    },
    LOADROLEPERMISSION(state,payload){
        state.allRolePermission = payload;
    },
    LOADGAMES(state,payload){
        state.allgames = payload;
    }
}
//在这里进行异步数据请求，然后将请求到的数据提交到mutations里的函数进行状态的变更
const actions = {
    loadAllPermission({commit},payload){
        axios.get(apis.findPermissionMenage)
        .then((resp)=>{
            // console.log(resp)
            console.log(resp.data.allPermission)
            commit('LOADALLPERMISSIONS',resp.data.allPermission)
        })
    },
    loadrolepermission({commit},payload){
        axios.get(apis.roleMenage)
        .then((resp)=>{
            // console.log(resp)
            // console.log(resp.data)
            // console.log(resp.data.allRoles)
            commit('LOADROLEPERMISSION',resp.data.allRoles)
        })
    },
    //要使用必须加载，在mounted中
    loadgames({commit},payload){
        axios.get(apis.allgamesInfo)
        .then((resp)=>{
            console.log(resp.data.data[0].games)
            commit('LOADGAMES',resp.data.data[0].games)
        })
    }
}
export default {
    state,
    getters,
    mutations,
    actions
}
